using UnityEngine;
using UnityEngine.UI;

namespace Voodoo.Sauce.Internal.VoodooTune
{
	public class PinchableScrollRect : ScrollRect
	{
		[SerializeField]
		private float _minZoom = 0.1f;

		[SerializeField]
		private float _maxZoom = 10f;

		[SerializeField]
		private float _zoomLerpSpeed = 10f;

		private float _currentZoom = 1f;

		private bool _isPinching;

		private float _startPinchDist;

		private float _startPinchZoom;

		private Vector2 _startPinchCenterPosition;

		private Vector2 _startPinchScreenPosition;

		private float _mouseWheelSensitivity = 0.1f;

		private bool blockPan;

		protected override void Awake()
		{
			Input.multiTouchEnabled = true;
		}

		private void Update()
		{
			if (Input.touchCount == 2)
			{
				if (!_isPinching)
				{
					_isPinching = true;
					OnPinchStart();
				}
				OnPinch();
			}
			else
			{
				_isPinching = false;
				if (Input.touchCount == 0)
				{
					blockPan = false;
				}
			}
			float axis = Input.GetAxis("Mouse ScrollWheel");
			if (Mathf.Abs(axis) > float.Epsilon)
			{
				_currentZoom *= 1f + axis * _mouseWheelSensitivity;
				_currentZoom = Mathf.Clamp(_currentZoom, _minZoom, _maxZoom);
				_startPinchScreenPosition = Input.mousePosition;
				RectTransformUtility.ScreenPointToLocalPointInRectangle(base.content, _startPinchScreenPosition, null, out _startPinchCenterPosition);
				_ = (Vector2)new Vector3(base.content.pivot.x * base.content.rect.size.x, base.content.pivot.y * base.content.rect.size.y);
			}
			if (Mathf.Abs(base.content.localScale.x - _currentZoom) > 0.001f)
			{
				base.content.localScale = Vector3.Lerp(base.content.localScale, Vector3.one * _currentZoom, _zoomLerpSpeed * Time.deltaTime);
			}
		}

		protected override void SetContentAnchoredPosition(Vector2 position)
		{
			if (!_isPinching && !blockPan)
			{
				base.SetContentAnchoredPosition(position);
			}
		}

		private void OnPinchStart()
		{
			Vector2 position = Input.touches[0].position;
			Vector2 position2 = Input.touches[1].position;
			_startPinchDist = Distance(position, position2) * base.content.localScale.x;
			_startPinchZoom = _currentZoom;
			_startPinchScreenPosition = (position + position2) / 2f;
			RectTransformUtility.ScreenPointToLocalPointInRectangle(base.content, _startPinchScreenPosition, null, out _startPinchCenterPosition);
			blockPan = true;
		}

		private void OnPinch()
		{
			float num = Distance(Input.touches[0].position, Input.touches[1].position) * base.content.localScale.x;
			_currentZoom = num / _startPinchDist * _startPinchZoom;
			_currentZoom = Mathf.Clamp(_currentZoom, _minZoom, _maxZoom);
		}

		private float Distance(Vector2 pos1, Vector2 pos2)
		{
			RectTransformUtility.ScreenPointToLocalPointInRectangle(base.content, pos1, null, out pos1);
			RectTransformUtility.ScreenPointToLocalPointInRectangle(base.content, pos2, null, out pos2);
			return Vector2.Distance(pos1, pos2);
		}
	}
}
